package com.cardetective.shopcar.utils

import android.content.Context
import android.content.res.Configuration
import android.os.Build
import com.google.gson.Gson
import java.util.Locale


class LanguageUtil {

    companion object{
        val LOCALE_SP: String = "LOCALE_SP"
        val LOCALE_SP_KEY: String = "LOCALE_SP_KEY"
    }

    fun getLocale(context: Context): Locale {
        val spLocale = context.getSharedPreferences(LOCALE_SP, Context.MODE_PRIVATE)
        val localeJson = spLocale.getString(LOCALE_SP_KEY, "")
        val gson = Gson()
        return gson.fromJson(localeJson, Locale::class.java)
    }


    private fun setLocale(pContext: Context, pUserLocale: Locale) {
        val spLocal = pContext.getSharedPreferences(LOCALE_SP, Context.MODE_PRIVATE)
        val edit = spLocal.edit()
        val json = Gson().toJson(pUserLocale)
        edit.putString(LOCALE_SP_KEY, json)
        edit.apply()
    }


    fun updateLocale(context: Context, locale: Locale): Boolean {
        if (needUpdateLocale(context, locale)) {
            val configuration: Configuration = context.resources.configuration
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                configuration.setLocale(locale)
            } else {
                configuration.locale = locale
            }
            val displayMetrics = context.resources.displayMetrics
            context.resources.updateConfiguration(configuration, displayMetrics)
            setLocale(context, locale)
            return true
        }
        return false
    }

    fun needUpdateLocale(pContext: Context, newUserLocale: Locale?): Boolean {
        return newUserLocale != null && !getCurrentLocale(pContext).equals(newUserLocale)
    }

    fun getCurrentLocale(context: Context): Locale {
        val locale: Locale =
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //7.0有多语言设置获取顶部的语言
                context.resources.configuration.locales[0]
            } else {
                context.resources.configuration.locale
            }
        return locale
    }
}